import store from "@/core/store.js"
import request from "@/core/request"
import Md5 from 'js-md5'

/**
 * 存储数据
 */
const setSotrage = (key, value) => {
	uni.setStorage({
		data: typeof value == "object" ? JSON.stringify(value) : value,
		key
	})
}

/**
 * 获取数据
 */
const getStorage = (key) => {
	return uni.getStorageInfoSync(key)
}

/**
 * 生成随机数
 */
const getRnd = (min, max) => {
	return Math.floor(Math.random() * (max - min + 1)) + min
}

/**
 * 上传图片
 */
const uploadFile = (data) => {
	return new Promise(async (res, rej) => {
		uni.showLoading({
			mask: true,
			title: "正在上传。。。"
		})
		let imageBase64 = await imgToBase64(data.tempFilePath || data.url)
		await request({
			url: store.state.uploadUrl,
			method: 'post',
			dataType: "formData",
			data: {
				sanpPic: imageBase64
			},
		}).then(data => {
			res(data);
		}).catch(err => {
			uni.showToast({
				title: "上传文件失败",
				icon: "error"
			})
			// rej(err)
		}).finally(() => {
			uni.hideLoading();
		})
	})
}

/**
 * 验证
 * 0：值为空
 * 1：值格式错误
 * 2：值对
 */
const validateFunc = (value, type) => {
	if (!value) return 0;
	let emailRex = /^[\w-]+(.[\w-]+)*@[\w-]+(.[\w-]+)+$/;
	let telRex =
		/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[0-9]))\d{8}$/;
	let htmlRex = /<("[^"]*"|'[^']*'|[^'">])*>/g;
	let flag = true;
	switch (type) {
		case "email":
			flag = emailRex.test(value)
			break;
		case "tel":
			flag = telRex.test(value)
			break;
		case "html":
			flag = htmlRex.test(value)
			break;
	}
	return flag ? 2 : 1;
}
const sign = (data) => {
	let nonce = getRnd(100, 1000000000)
	let timestamp = new Date().getTime()
	let str = `timestamp=${timestamp}&appKey=ChongqingZhaopin$123@@,.&nonce=${nonce}`
	let dataStr = "";
	for (let key in data) {
		dataStr += `${key}=${data[key]}&`
	}
	console.log(dataStr + str)
	let header = {
		nonce,
		timestamp,
		sign: Md5(dataStr + str),
	}
	return header
}

/**
 * 将图片转为base64
 * @param {Object} filePath
 */
function imgToBase64(filePath) {
	return new Promise((resolve, reject) => {
		let baseFormat = 'data:image/png;base64,'
		let base64 = wx.getFileSystemManager().readFileSync(filePath, 'base64')
		resolve(baseFormat + base64)
	})
}

function isPlainObject(val) {
	return val !== null && typeof val === 'object' && !Array.isArray(val);
}

function pickExclude(obj, keys) {
	if (!isPlainObject(obj)) {
		return {};
	}
	return Object.keys(obj).reduce((prev, key) => {
		if (!keys.includes(key)) {
			prev[key] = obj[key];
		}
		return prev;
	}, {});
}

function formatImage(res) {
	return res.tempFiles.map((item) => (Object.assign(Object.assign({}, pickExclude(item, [
		'path'
	])), {
		type: 'image',
		url: item.tempFilePath || item.path,
		thumb: item.tempFilePath ||
			item.path
	})));
}

export {
	getRnd,
	uploadFile,
	validateFunc,
	sign,formatImage
}